import React, { Component } from 'react'
import {
  Select,
  Button,
  Table,
  Modal,
  Input,
  DatePicker,
  Form,
  message,
  Tooltip,
  Space,
} from 'antd'
import {
  PlusOutlined,
  DeleteOutlined,
  DeleteFilled,
  EditOutlined,
} from '@ant-design/icons'
import 'antd/dist/antd.css'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { getDictionaryLabel } from '../../rudexRou/OperatesCookie.js'
import AdvancedSearchForm from '../../componentJsx/common/searchForm'
import '../../componentCss/component.css'
import HasPermi from '../../componentJsx/common/hasPermi'
import EditForm from '../../componentJsx/common/editForm'
import { confirmDeptByCode } from '../../utils'
import {
  certificateAdd,
  certificateEdit,
  certificateDel,
  queryCertificatePage,
} from '../../api'
const { Option } = Select

class CertificateConfig extends Component {
  constructor(props) {
    super(props)
    this.state = {
      total: 0,
      pageSize: 10,
      page: 1,
      modelTitle: '',
      loading: false,
      isEditVisible: false, // 修改模态框状态
      isDelVisible: false, // 导出模态框状态
      confirmLoading: false, // 确认按钮状态
      dataList: [], // 表格数据
      searchParams: {},
      // 表格列配置
      columns: [
        {
          title: '证书名称',
          dataIndex: 'name',
          key: 'name',
          ellipsis: true,
          width: 200,
        },
        {
          title: '证书类型',
          dataIndex: 'type',
          key: 'type',
          width: 80,
          render: (text) =>
            text ? getDictionaryLabel('certificateType', text) : text,
        },
        {
          title: '证书级别',
          dataIndex: 'level',
          key: 'level',
          width: 80,
          render: (text) =>
            text ? getDictionaryLabel('examLevel', text) : text,
        },
        {
          title: '证书信息',
          dataIndex: 'info',
          key: 'info',
          ellipsis: true,
          width: 180,
        },
        {
          title: '时间跨度（月）',
          dataIndex: 'duration',
          key: 'duration',
          ellipsis: true,
          width: 120,
        },
        {
          title: '关联科目',
          dataIndex: 'subjects',
          key: 'subjects',
          ellipsis: true,
          width: 120,
          render: (text) => {
            if (text) {
              const arr = text.split(',')
              const subjectsList = []
              arr.forEach((item) => {
                subjectsList.push(getDictionaryLabel('examSubject', item))
              })
              return subjectsList.join(' , ')
            } else {
              return ''
            }
          },
        },
        {
          title: '证书有效期（月）',
          dataIndex: 'validityTime',
          key: 'validityTime',
          ellipsis: true,
          width: 140,
        },
        {
          title: '最近修改人',
          dataIndex: 'updateUser',
          key: 'updateUser',
          ellipsis: true,
          width: 100,
        },
        {
          title: '最近修改时间',
          dataIndex: 'updateTime',
          key: 'updateTime',
          ellipsis: true,
          width: 160,
        },
        {
          title: '操作',
          key: 'action',
          width: 80,
          fixed: 'right',
          render: (text, record) => (
            <Space size="middle">
              <Tooltip title="编辑">
                <div style={{ width: 30 }}>
                  <HasPermi
                    bottonData={{
                      type: 'link',
                      interceptor: 'tmfs:certificateConfig:edit',
                      clickFn: () => this.editItem(record),
                      icon: <EditOutlined />,
                    }}
                  />
                </div>
              </Tooltip>
            </Space>
          ),
        },
      ],
      // 查询条件项配置
      searchForm: [
        {
          key: 1,
          type: 'input',
          name: '证书名称',
          code: 'name',
          maxLength: 20,
          placeholder: '请输入名称',
        },
        {
          key: 3,
          type: 'select',
          name: '证书类型',
          code: 'type',
          options: getDictionaryLabel('certificateType'),
        },
        {
          key: 3,
          type: 'select',
          name: '证书级别',
          code: 'level',
          options: getDictionaryLabel('examLevel'),
        },
      ],
      bottonList: [
        {
          interceptor: 'tmfs:certificateConfig:add',
          type: 'primary',
          clickFn: this.addModal,
          icon: <PlusOutlined />,
          text: '新增',
        },
        {
          interceptor: 'tmfs:certificateConfig:del',
          type: 'danger',
          clickFn: () => this.showDelModal(null),
          icon: <DeleteOutlined />,
          text: '删除',
        },
      ],
      selectedRowKeys: [], // 选择行Key集合
      selectedRows: [], // 选择行集合
      selectedRow: {}, // 修改行数据
      editFormConfig: [],
      // 备选人员数据
      // empList: JSON.parse(localStorage.getItem('empList')),
    }
  }
  componentWillMount() { }
  componentDidMount() {
    this.getData()
  }
  addModal = () => {
    const editFormConfig = [
      {
        type: 'select',
        name: '证书类型',
        code: 'type',
        options: getDictionaryLabel('certificateType'),
        rules: [
          {
            required: true,
            message: '请选择证书类型',
          },
        ],
      },
      {
        type: 'input',
        name: '证书名称',
        code: 'name',
        maxLength: 20,
        rules: [
          {
            required: true,
            message: '请输入证书名称',
          },
        ],
      },
      {
        type: 'select',
        name: '证书级别',
        code: 'level',
        options: getDictionaryLabel('examLevel'),
        rules: [
          {
            required: true,
            message: '请选择证书级别',
          },
        ],
      },
      {
        type: 'inputNumber',
        name: '时间跨度（月）',
        code: 'duration',
        min: 0,
        max: 150,
        rules: [
          {
            required: true,
            message: '请输入时间跨度',
          },
        ],
      },
      {
        type: 'multipleSelect',
        name: '关联科目',
        code: 'subjects',
        options: getDictionaryLabel('examSubject'),
        rules: [
          {
            required: true,
            message: '请选择关联科目',
          },
        ],
      },
      {
        type: 'inputNumber',
        name: '证书有效期（月）',
        code: 'validityTime',
        min: 0,
        max: 150,
        rules: [
          {
            required: true,
            message: '请输入证书有效期',
          },
        ],
      },
      {
        type: 'input',
        name: '证书信息',
        code: 'info',
        maxLength: 50,
      },
    ]
    this.setState(
      {
        editFormConfig: editFormConfig,
        isEditVisible: true,
        modelTitle: '新增',
      },
      () => {
        //填充当前选中行的数据
        this.editFormRef.setValues({ duration: 12, validityTime: 36 })
        // this.modifyFormRef.current.setFieldsValue(this.state.selectedRow)
      }
    )
  }
  editItem = (item) => {
    const editFormConfig = [
      {
        type: 'select',
        name: '证书类型',
        code: 'type',
        options: getDictionaryLabel('certificateType'),
      },
      {
        type: 'input',
        name: '名称',
        code: 'name',
        maxLength: 20,
        rules: [
          {
            required: true,
            message: '请输入证书名称',
          },
        ],
      },
      {
        type: 'select',
        name: '证书级别',
        code: 'level',
        options: getDictionaryLabel('examLevel'),
      },
      {
        type: 'inputNumber',
        name: '时间跨度（月）',
        code: 'duration',
        min: 0,
        max: 150,
        rules: [
          {
            required: true,
            message: '请输入时间跨度',
          },
        ],
      },
      {
        type: 'multipleSelect',
        name: '关联科目',
        code: 'subjects',
        options: getDictionaryLabel('examSubject'),
        rules: [
          {
            required: true,
            message: '请选择关联科目',
          },
        ],
      },
      {
        type: 'inputNumber',
        name: '证书有效期（月）',
        code: 'validityTime',
        min: 0,
        max: 150,
        rules: [
          {
            required: true,
            message: '请输入证书有效期',
          },
        ],
      },
      {
        type: 'input',
        name: '证书信息',
        code: 'info',
        maxLength: 50,
      },
    ]
    const itemInfo = JSON.parse(JSON.stringify(item))
    itemInfo.subjects = itemInfo.subjects.split(',')
    this.setState(
      {
        editFormConfig: editFormConfig,
        selectedRow: itemInfo,
        isEditVisible: true,
        modelTitle: '修改',
      },
      () => {
        //填充当前选中行的数据
        this.editFormRef.setValues(this.state.selectedRow)
        // this.modifyFormRef.current.setFieldsValue(this.state.selectedRow)
      }
    )
  }
  getData = () => {
    this.setState({ loading: true, dataList: [] })
    queryCertificatePage(
      Object.assign(
        {},
        {
          currentPage: this.state.page,
          pageSize: this.state.pageSize,
        },
        this.state.searchParams
      )
    ).then((response) => {
      let dataList = []
      if (response.data.code === 200) {
        if (response.data && response.data.data) {
          const rsp = response.data.data
          dataList = rsp.list
          this.setState({ total: rsp.total })
        }
      } else {
        // message.error('查询数据失败!')
        message.error(response.data.message || '查询数据失败!')

      }
      this.setState({
        dataList: dataList,
        loading: false,
        selectedRowKeys: [],
        selectedRows: [],
      })
    })
  }
  showDelModal = () => {
    this.setState({ isDelVisible: true })
  }
  handleDelOk = () => {
    this.buttonLoading(true)
    certificateDel(this.state.selectedRowKeys.join(',')).then((response) => {
      if (response.data.code === 200) {
        message.success('删除数据成功!')
        this.getData()
      } else {
        message.error(response.data.message || '删除数据失败!')
      }
      this.buttonLoading(false)
      this.setState({ isDelVisible: false })
    })
  }
  handleEditOk = () => {
    this.buttonLoading(true)
    this.editFormRef
      .validateFields()
      .then(() => {
        const obj = this.editFormRef.getValues(true)
        obj.subjects = obj.subjects.join(',')
        if (this.state.modelTitle === '修改') {
          certificateEdit(
            Object.assign({}, obj, {
              id: this.state.selectedRow.id,
            })
          ).then((response) => {
            if (response.data.code === 200) {
              message.success('修改数据成功!')
              this.getData()
            } else {
              message.error(response.data.message || '修改数据失败!')
            }
            this.buttonLoading(false)
            this.setState({ isEditVisible: false })
            this.editFormRef.resetFields()
          })
        } else {
          certificateAdd(obj).then((response) => {
            if (response.data.code === 200) {
              message.success('新增数据成功!')
              this.getData()
            } else {
              message.error(response.data.message || '新增数据失败!')
            }
            this.buttonLoading(false)
            this.setState({ isEditVisible: false })
            this.editFormRef.resetFields()
          })
        }
      })
      .catch(() => {
        this.buttonLoading(false)
      })
  }
  handleCancel = () => {
    if (this.state.isEditVisible) {
      this.editFormRef.resetFields()
    }
    this.setState({
      isEditVisible: false,
      isDelVisible: false,
    })
  }
  execSearch = (data) => {
    const param = {}
    for (var key in data) {
      if (data[key]) {
        param[key] = data[key]
      }
    }
    this.setState({ searchParams: param, page: 1 }, () => {
      this.getData()
    })
  }
  //修改页数changePage
  changePage = (page, pageSize) => {
    this.setState({
      page,
      pageSize,
    })
    this.setState(
      {
        page,
        pageSize,
      },
      () => {
        this.getData()
      }
    )
  }
  buttonLoading = (flag) => {
    this.setState({ confirmLoading: flag })
  }
  onRef = (ref) => {
    this.editFormRef = ref
  }
  modifyFormRef = React.createRef() //绑定修改信息表单
  render() {
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        })
      },
      getCheckboxProps: (record: DataType) => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    }
    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    }
    return (
      <div>
        <div className="myProjectsBody">
          <div className="tabstyle">
            <div className="bigContent1" id="projectDetail">
              <AdvancedSearchForm
                execSearch={this.execSearch}
                formData={this.state.searchForm}
              />
            </div>
          </div>
          <div className="segmentationDiv"></div>
          <div className="tabstyle">
            <div className="bigContent1" id="projectDetail">
              <div className="operatingDiv">
                {this.state.bottonList.map((item) => (
                  <HasPermi key={item.interceptor} bottonData={item} />
                ))}
              </div>
              <div className="tableDiff">
                <Table
                  rowSelection={{
                    type: 'checkbox',
                    ...rowSelection,
                  }}
                  loading={this.state.loading}
                  dataSource={this.state.dataList}
                  // scroll={{ x: '100vw' }}
                  bordered
                  columns={this.state.columns}
                  rowKey={(record) => record.id}
                  pagination={{
                    total: this.state.total,
                    pageSize: this.state.pageSize,
                    current: this.state.page,
                    showSizeChanger: true,
                    onChange: this.changePage,
                    showTotal: (total) => '共 ' + total + ' 条',
                  }}
                ></Table>
              </div>
            </div>
          </div>
        </div>

        <Modal
          width="500px"
          title="删除提示"
          visible={this.state.isDelVisible}
          onOk={() => this.handleDelOk()}
          confirmLoading={this.state.confirmLoading}
          onCancel={() => this.handleCancel()}
          cancelText="取消"
          okText="确认删除"
        >
          <DeleteFilled
            style={{
              fontSize: '28px',
              color: '#e00',
              float: 'left',
              backgroundColor: '#f002',
              padding: 8,
              borderRadius: '50%',
            }}
          />
          <div
            style={{
              fontSize: 14,
              marginLeft: 60,
              height: 22,
              lineHeight: '22px',
              fontWeight: 700,
              color: '#666',
            }}
          >
            删除所选数据？
          </div>
          <div
            style={{
              fontSize: 14,
              marginLeft: 60,
              height: 22,
              lineHeight: '22px',
              color: '#e00',
            }}
          >
            删除后数据不可恢复，请确认是否删除选中的证书配置信息？
          </div>
        </Modal>
        <Modal
          title={this.state.modelTitle}
          type="primary"
          okText="确认"
          cancelText="取消"
          visible={this.state.isEditVisible}
          confirmLoading={this.state.confirmLoading}
          onOk={this.handleEditOk}
          onCancel={this.handleCancel}
        >
          <EditForm onRef={this.onRef} formData={this.state.editFormConfig} />
        </Modal>
      </div>
    )
  }
}
export default CertificateConfig
